package com.supplychain.financial.parent.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.TmcMessage;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.request.TmcMessagesConfirmRequest;
import com.taobao.api.request.TmcMessagesConsumeRequest;
import com.taobao.api.response.TmcMessagesConfirmResponse;
import com.taobao.api.response.TmcMessagesConsumeResponse;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Copyright 2016 Drgon。LT
 * @类的作用：短信工具,淘宝阿里大鱼
 * @author huangqianhai@combinedpay.com
 * @创建时间:2016年8月10日下午3:37:38
 * @版本号:1.0 
 * @修改人:
 * @修改时间:
 */
public class SMSUtil {
	
	private static String verifyCode = "";
	private static String inviteCode = "";
	private static String exchangeCode = "";
	
	/**
	 * 日志变量
	 */
	private static Logger log = Logger.getLogger(SMSUtil.class);
	/**
	 * 连接客户端
	 */
	private static TaobaoClient client =  new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23514915", "e99b608cf7fb2d1369451770a2eecb1e");
	/**
	 * 1.1 登录验证验证码
	 * @param code 验证码
	 * @param phone 手机号
	 */
	public static void sendCode(String phone,String code){ 
		try {
			AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
			req.setSmsType("normal");
			req.setSmsFreeSignName("社区云超市");
			Map param = new HashMap();
			param.put("productName", "社区云超市");
			param.put("code", code);
			req.setSmsParamString(new ObjectMapper().writeValueAsString(param));
			req.setRecNum(phone.trim());
			req.setSmsTemplateCode(verifyCode);//短信模板
		    client.execute(req); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 1.2 邀请码
	 * @param code 验证码
	 * @param phone 手机号
	 */
	public static void sendInvitedCode(String phone,String userName){ 
		try {
			//TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23399543", "9a4a15229857749036e2b32ca30a9a28");
			AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
			req.setSmsType("normal");
			req.setSmsFreeSignName("社区云超市");
			Map param = new HashMap();
			param.put("productName", "社区云超市");
			param.put("manager", userName);
			req.setSmsParamString(new ObjectMapper().writeValueAsString(param));
			req.setRecNum(phone.trim());
			req.setSmsTemplateCode(inviteCode);//短信模板
		    client.execute(req); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 1.3 活动码
	 * @param code 验证码
	 * @param phone 手机号
	 */
	public static void sendExchangeCode(String phone,String code){ 
		try {
			//TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23399543", "9a4a15229857749036e2b32ca30a9a28");
			AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
			req.setSmsType("normal");
			req.setSmsFreeSignName("社区云超市");
			Map param = new HashMap();
			param.put("exchange",code);
			req.setSmsParamString(new ObjectMapper().writeValueAsString(param));
			req.setRecNum(phone.trim());
			req.setSmsTemplateCode(exchangeCode);//短信模板
		    client.execute(req); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	/**
	 * 支付失败验证码 eg:尊敬的${name}，您的${money}金额的${order}订单于${time}支付失败
	 * @param cust_code
	 * @param co_num
	 * @param amount
	 * @param trans_date
	 * @param phone
	 */
	 public static void sendOrderSMS(String custcode,String orderno,String orderamount,String orderdate,String phone){
		 try {
				//TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23399543", "9a4a15229857749036e2b32ca30a9a28");
				AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
				req.setSmsType("normal");
				req.setSmsFreeSignName("社区云超市");
				Map param = new HashMap();
				param.put("name",custcode);
				param.put("money",orderamount);
				param.put("order",orderno);
				param.put("time", orderdate);
				req.setSmsParamString(new ObjectMapper().writeValueAsString(param));
				req.setRecNum(phone.trim());
				req.setSmsTemplateCode("SMS_43185045");//短信模板
			    client.execute(req); 
			} catch (Exception e) {
				e.printStackTrace();
			}
	 }
	 
	 /**
	  * 支付失败银联返回状态05验证码 eg:您的客户${name}，有一条${money}金额的${order}订单于${time}交易受理中，请及时查询
	  * @param custcode
	  * @param orderno
	  * @param orderamount
	  * @param orderdate
	  * @param phone
	  */
	 public static void sendOrder05SMS(String custcode,String orderno,String orderamount,String orderdate,String phone){
		 try {
				//TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23399543", "9a4a15229857749036e2b32ca30a9a28");
				AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
				req.setSmsType("normal");
				req.setSmsFreeSignName("社区云超市");
				Map param = new HashMap();
				param.put("name",custcode);
				param.put("money",orderamount);
				param.put("order",orderno);
				param.put("time", orderdate);
				req.setSmsParamString(new ObjectMapper().writeValueAsString(param));
				req.setRecNum(phone.trim());
				req.setSmsTemplateCode("SMS_74755004");//短信模板
			    client.execute(req); 
			} catch (Exception e) {
				e.printStackTrace();
			}
	 }
	 
	 /**
	  * 您的客户${name}，有一条${money}金额的${order}订单于${time}通知失败
	  * @param custcode
	  * @param orderno
	  * @param orderamount
	  * @param orderdate
	  * @param phone
	  */
	 public static void sendOrderNotifySMS(String custcode,String orderno,String orderamount,String orderdate,String phone){
		 try {
				//TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23399543", "9a4a15229857749036e2b32ca30a9a28");
				AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
				req.setSmsType("normal");
				req.setSmsFreeSignName("社区云超市");
				Map param = new HashMap();
				param.put("name",custcode);
				param.put("money",orderamount);
				param.put("order",orderno);
				param.put("time", orderdate);
				req.setSmsParamString(new ObjectMapper().writeValueAsString(param));
				req.setRecNum(phone.trim());
				req.setSmsTemplateCode("SMS_47495162");//短信模板
			    client.execute(req); 
			} catch (Exception e) {
				e.printStackTrace();
			}
	 }
	 
	 
	 /**
	  * 尊敬的客户{custom}我是客户经理${manager}，邀请您参与订烟自动支付体验活动。点击认证网址:http://test.combinedpay.cn:28100/web/download/index.html 也可直接回“复烟草专卖证号+新商盟登录密码”（注意专卖证号与密码之间用+连接）。如有疑问请直接联系你的烟草公司客户经理。
	  * @param custcode
	  * @param orderno
	  * @param orderamount
	  * @param orderdate
	  * @param phone
	  */
	 public static void managerInviteCustomer(String custom,String manager,String phone){
		 try {
				//TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23399543", "9a4a15229857749036e2b32ca30a9a28");
				AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
				req.setSmsType("normal");
				req.setSmsFreeSignName("社区云超市");
				Map param = new HashMap();
				param.put("customer",custom);
				param.put("manager",manager);
				req.setSmsParamString(new ObjectMapper().writeValueAsString(param));
				req.setRecNum(phone.trim());
				req.setSmsTemplateCode("SMS_77690034");//短信模板
			    client.execute(req); 
			} catch (Exception e) {
				e.printStackTrace();
			}
	 }
	 
	 
	 
	static{
		try {
			Properties prop = new Properties();
			InputStream in = SMSUtil.class.getClassLoader().getResourceAsStream("sms.properties");
			prop.load(in);
			verifyCode = prop.getProperty("verify_code");
			inviteCode = prop.getProperty("invite_code");
			exchangeCode = prop.getProperty("exchange_code");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 短信接口测试
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		//sendExchangeCode("13310403200","123456");
		managerInviteCustomer("张三", "李四", "18259286501");
		
//		TmcClient client = new TmcClient("23514915", "e99b608cf7fb2d1369451770a2eecb1e", "default");
//		client.connect("ws://mc.api.taobao.com/");
//		for (int i = 0; i < 10; i++) {
//		    client.send("helloworld-topic", "{helloworld-content}", "session_key");
//		}
		
		do {
		    long quantity = 100L;
		    TmcMessagesConsumeResponse rsp = null;
		    do {
		        TmcMessagesConsumeRequest req = new TmcMessagesConsumeRequest();
		        req.setQuantity(quantity);
		        req.setGroupName("default");
		        rsp = client.execute(req);
		        if (rsp.isSuccess() && rsp.getMessages() != null) {
		            for (TmcMessage msg : rsp.getMessages()) {
		                // handle message
		                System.out.println(msg.getContent());
		                System.out.println(msg.getTopic());
		                // confirm message
		                TmcMessagesConfirmRequest cReq = new TmcMessagesConfirmRequest();
		                cReq.setGroupName("default");
		                cReq.setsMessageIds(String.valueOf(msg.getId()));
		                TmcMessagesConfirmResponse cRsp = client.execute(cReq);
		                System.out.println(cRsp.getBody());
		            }
		        }
		        System.out.println(rsp.getBody());
		    } while (rsp != null && rsp.isSuccess() && rsp.getMessages() != null && rsp.getMessages().size() == quantity);
		    Thread.sleep(1000L);
		} while (true);
		
		
//		TmcClient client = new TmcClient("23514915", "e99b608cf7fb2d1369451770a2eecb1e","default");
//		client.setMessageHandler(new MessageHandler() {
//			
//			@Override
//			public void onMessage(Message message, MessageStatus status) throws Exception {
//				// TODO Auto-generated method stub
//				try {
//					System.out.println(message.getContent());
//					System.out.println(message.getTopic());
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					status.fail();
//					e.printStackTrace();
//				}
//			}
//		});
//		client.connect("ws://mc.api.taobao.com"); 
//		Thread.sleep(10000);
	}
}
